package com.shangsheng.dao;
import com.dangdang.ddframe.rdb.sharding.api.ShardingDataSourceFactory;
import com.dangdang.ddframe.rdb.sharding.api.rule.DataSourceRule;
import com.dangdang.ddframe.rdb.sharding.api.rule.ShardingRule;
import com.dangdang.ddframe.rdb.sharding.api.rule.TableRule;
import com.dangdang.ddframe.rdb.sharding.api.strategy.database.DatabaseShardingStrategy;
import com.dangdang.ddframe.rdb.sharding.api.strategy.table.TableShardingStrategy;
import com.shangsheng.controller.ModuloDatabaseShardingAlgorithm;
import com.shangsheng.controller.ModuloTableShardingAlgorithm;

import org.apache.commons.dbcp.BasicDataSource;

import javax.sql.DataSource;

import java.sql.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class ShardingjdbcTest {
    private  static String url="jdbc:mysql://localhost:3306/%s?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC\n&useSSL=true";
    private static String driverClass="com.mysql.cj.jdbc.Driver";
    private static DataSource createDataSource(final String dataSourceName) {
        BasicDataSource result = new BasicDataSource();
        result.setDriverClassName(driverClass);
        result.setUrl(String.format(url, dataSourceName));
        result.setUsername("root");
        result.setPassword("");
        return result;
    }
    public static void main(String[] args) throws SQLException {
        Map<String,DataSource> dataSourceMap =new HashMap<>(2);
        dataSourceMap.put("db0",createDataSource("db0"));
        dataSourceMap.put("db1",createDataSource("db1"));
        DataSourceRule dataSourceRule = new DataSourceRule(dataSourceMap);

        TableRule orderTableRule = TableRule.builder("t_order")
                .actualTables(Arrays.asList("t_order_0"))
                .dataSourceRule(dataSourceRule)
                .build();

        ShardingRule shardingRule = ShardingRule.builder()
                .dataSourceRule(dataSourceRule)
                .tableRules(Arrays.asList(orderTableRule))
               // .databaseShardingStrategy(new DatabaseShardingStrategy("user_id", new ModuloDatabaseShardingAlgorithm()))
               // .tableShardingStrategy(new TableShardingStrategy("order_id", new ModuloTableShardingAlgorithm()))
                .build();

        DataSource dataSource = ShardingDataSourceFactory.createDataSource(shardingRule);

        String sql = "insert into t_order VALUES(89,89) ";
        try {
            Connection conn = dataSource.getConnection();
            Statement statement = conn.createStatement();
            statement.executeUpdate(sql);
            statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

}
